﻿using KafkaSDK;
using OldMvcDemo.DALs;
using OldMvcDemo.Models;
using RishCenter.HttpApi.Client;

namespace OldMvcDemo.BLLs;

public class PaymentBLL
{
    private readonly AccountDAL _AccountDAL;//操作数据库
    private readonly KafkaTemplate<string, string> _KafkaTemplate;//操作kafka
    private readonly RishCheckService _RishCheckService;//风控微服务接口

    private const string TOPIC_AUDIT_LOG = "topic_audit_log";

    public PaymentBLL(
        AccountDAL accountDAL,
        KafkaTemplate<string, string> kafkaTemplate,
        RishCheckService rishCheckService
        )
    {
        _AccountDAL = accountDAL;
        _KafkaTemplate = kafkaTemplate;
        _RishCheckService = rishCheckService;
    }

    public async Task<PayResult> PayAsync(
        Guid userId,
        string merchantAccountNo,
        decimal amount)
    {
        //1. 从数据库读取数据
        var clientAccount = await _AccountDAL.GetAccountByIdAsync(userId);
        var merchantAccount = await _AccountDAL.GetAccountByNoAsync(merchantAccountNo);
        //2. 业务参数校验
        if (clientAccount.Balance < amount)
        {
            throw new UserFriendlyException("余额不足", "NoMoney");
        }
        //3. 调用风控微服务
        var rishCode = await _RishCheckService.CheckPaymentAsync(userId, merchantAccountNo, amount);
        //4. 校验校验合法性
        if (!"0000".Equals(rishCode))
        {
            throw new UserFriendlyException("风控验证不通过", "InvalidOper");
        }
        //5. 计算新值，并且更新字段
        clientAccount.Balance -= amount;
        merchantAccount.Balance += amount;
        //6. 更新到数据库
        await _AccountDAL.UpdateAsync(clientAccount);
        await _AccountDAL.UpdateAsync(merchantAccount);
        //7. 发送审计消息
        var message = $"Kafka message:{userId},{merchantAccountNo},{merchantAccount.Balance}";
        await _KafkaTemplate.SendAsync(TOPIC_AUDIT_LOG, message);
        return new PayResult
        {
            IsSuccess = true,
        };
    }
}
